package com.isman.domain;

import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;

@Entity
public class User {

	@Id
	@Column(name = "id")
	private int id;

	@Column(name = "type")
	private Boolean type; 

	@Column(name = "name")
	private String name;
	
	@JoinColumn(name = "parent_id")
	@ManyToOne(fetch = FetchType.LAZY)
	private User parent;
	
	@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
	private List<User> parents;
	

	public User getParent() {
		return parent;
	}

	public void setParent(User parent) {
		this.parent = parent;
	}

	public List<User> getParents() {
		return parents;
	}

	public void setParents(List<User> parents) {
		this.parents = parents;
	}

	public User() {
	}

	@PrePersist
	public void ensureId() {
		/*
		try {
			EntityManager em = EMF.getInstance().createEntityManager();
			String param = (type == true ? "1" : "0") + "%";
			
			
			
			EntityTransaction tx = em.getTransaction();
			tx.begin();
			CriteriaBuilder cb = em.getCriteriaBuilder();
			CriteriaQuery<Long> query = cb.createQuery(Long.class);
			
			
			
			Root<User> user = query.from(User.class);
			
			query.select(cb.count(user));
			query.where(cb.like(user.<String>get("id"), cb.parameter(String.class, "param")));
			
			
			TypedQuery<Long> tq = em.createQuery(query);
			tq.setParameter("param", param);
			Long count = tq.getSingleResult();

			tx.commit();
			this.id = (type == true ? "1" : "0") + String.format("%05d", count);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			EntityManager em = EMF.getInstance().createEntityManager();
			String param = (type == true ? "1" : "0") + "%";
			
			
			
			EntityTransaction tx = em.getTransaction();
			tx.begin();
			
			EasyCriteria<User> criteria = EasyCriteriaFactory.createQueryCriteria(em, User.class);
			criteria.andStringLike("id", param);
			
			
			Long count = criteria.count();

			tx.commit();
			this.id = (type == true ? "1" : "0") + String.format("%05d", count);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
		
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", type=" + type + ", name=" + name + "]";
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public Boolean getType() {
		return type;
	}

	public void setType(Boolean type) {
		this.type = type;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
